package com.bang.study.day01.queue;

/**
 * @Auther: Bang
 * @Date: 2019/9/10 0010 11:57
 * @Description: 基于有尾指针的链表实现的队列  FIFO(先进先出)
 */
public class LinkedListQueue<E> implements Queue<E> {


    private Node head;

    private Node tail;

    private int size;


    public LinkedListQueue() {
        head = null;
        tail = null;
        size = 0;
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * 入队 从链表尾部入队
     * @param e
     */
    @Override
    public void enqueue(E e) {
        Node next = new Node(e);
        if (tail==null) {
            tail = next;
            head = tail;
        }else{
            tail.next = next;
            tail = next;
        }
        size++;
    }

    /**
     * 出队 从链表首部出队
     * @return
     */
    @Override
    public E dequeue() {
        if (isEmpty()) {
            throw new IllegalArgumentException("QUEUE IS empty");
        }
        Node ret = this.head;
        head = head.next;
        size--;
        return ret.e;
    }

    @Override
    public E getFront() {
        if (isEmpty()) {
            throw new IllegalArgumentException("QUEUE IS empty");
        }
        return head.e;
    }

    @Override
    public String toString() {
        Node currrent = this.head;
        StringBuffer sb = new StringBuffer();
        sb.append("head [");
        while (currrent!=null){
            sb.append(currrent.e).append(" ");
            currrent = currrent.next;
        }
        sb.append("] tail");
        return "LinkedListQueue{" +
                ", queue=" + sb.toString() +
                ", size=" + size +
                '}';
    }

    private class Node{
        public E e;
        public Node next;

        public Node() {
        }

        public Node(E e, Node next) {
            this.e = e;
            this.next = next;
        }

        public Node(E e) {
            this.e = e;
        }

        @Override
        public String toString() {
            return "Node{" +
                    "e=" + e.toString() +
                    '}';
        }
    }


    public static void main(String[] args) {
        LinkedListQueue<Integer> listQueue = new LinkedListQueue<>();
        for (int i = 0; i < 10; i++) {
            listQueue.enqueue(i);
            System.out.println(listQueue);
        }
        System.out.println("---------------------");
        while (!listQueue.isEmpty()){
            listQueue.dequeue();
            System.out.println(listQueue);
        }

    }

}
